package com.siwei.mes.job;

import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.entity.Serial;
import com.siwei.mes.mapper.SerialMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.annotation.Resource;
import java.util.List;

/**
 * 定时清空
 *
 * @Description: 定时清空
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2024/1/28 21:47
 */
@Component
public class CleanSerialJob {
    private static final Logger log = LoggerFactory.getLogger("job");
    @Resource
    private SerialMapper serialMapper;

    /**
     * 自动清空表数据 每天0点清空一次
     */
    @Scheduled(cron = "0 0 0 * * ? ")
    public void init() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        String year = DateHelper.getYear() < 10 ? "0" + DateHelper.getYear() : DateHelper.getYear().toString();
        String month = DateHelper.getMonth() < 10 ? "0" + DateHelper.getMonth() : DateHelper.getMonth().toString();
        String day = DateHelper.getDay() < 10 ? "0" + DateHelper.getDay() : DateHelper.getDay().toString();
        log.info("定时清空序号表开始");
        /**查询所有的数据*/
        List<Serial> serialList = serialMapper.selectAll();
        for (Serial serial : serialList) {
            serial.setSerialYear(year);
            serial.setSerialMonth(month);
            serial.setSerialDay(day);
            serial.setSerialNumber(year.substring(2, 4) + month + day + "000");
            serialMapper.updateByPrimaryKeySelective(serial);
        }
        stopWatch.stop();
        log.info("定时清空序号表完成,耗时：{}s", stopWatch.getTotalTimeMillis() / 1000);
    }

    public static void main(String[] args) {
        Integer year = DateHelper.getYear();
        Integer month = DateHelper.getMonth();
        Integer day = DateHelper.getDay();
        String format = String.format(year.toString().substring(2, 4) + month + day + "%03d", 0);
        System.out.println(format);
    }
}
